package com.wennn.top.web.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.cache.RedisUtils;
import com.wennn.top.core.exception.WBusiException;
import com.wennn.top.core.mybatis.vo.PageResult;
import com.wennn.top.security.util.ContextUtil;
import com.wennn.top.shop.biz.order.entity.YxStoreOrder;
import com.wennn.top.shop.biz.order.service.IYxStoreOrderService;
import com.wennn.top.util.ConstUtil;
import com.wennn.top.web.order.dto.OrderComputedDto;
import com.wennn.top.web.order.dto.OrderCreateDto;
import com.wennn.top.web.order.vo.ConfirmOrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: 订单模块
 * @author: wennn
 * @date: 7/8/20
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单模块")
public class StoreOrderRest {

    @Autowired
    IYxStoreOrderService service;

    @Autowired
    RedisUtils redisUtils;

    @ApiOperation(value = "获取各状态的订单", notes = "当前用户的订单，待付款，已付款。。。")
    @GetMapping("/list/{pageNo}/{pageSize}")
    public IResult list(@PathVariable("pageNo") int pageNo, @PathVariable("pageSize") int pageSize, @RequestParam("type") String type) {
        LambdaQueryWrapper<YxStoreOrder> queryWrapper = Wrappers.lambdaQuery(YxStoreOrder.class);
        queryWrapper.eq(YxStoreOrder::getStatus, type).eq(YxStoreOrder::getUid, ContextUtil.getUid()).orderByAsc(YxStoreOrder::getAddTime, YxStoreOrder::getPayTime);
        Page page = new Page(pageNo, pageSize);
        page = service.page(page, queryWrapper);
        return PageResult.builder(page);
    }

    @ApiOperation(value = "获取各状态订单数量", notes = "当前用户订单数量，待付款，已付款。。。")
    @GetMapping("/data/{type}")
    public IResult data(@PathVariable(value = "type", required = false) String type) {
        List<Map<String, Integer>> maps = service.statusCount(type, ContextUtil.getUid() + "");

        Map result = maps.parallelStream().reduce((map, m2) -> {
            m2.put(map.get("STATUS").toString(), map.get("NUM"));
            return m2;
        }).get();
        return IResult.ok(result);
    }

    @ApiOperation(value = "订单 预生成", notes = "通过购物车id 来生成订单信息 产生orderKey --> 提交订单 or 取消")
    @PostMapping("/confirm")
    public IResult confirm(@RequestBody String[] cartIds) {
        ConfirmOrderVo confirmVo = service.confirm(cartIds);
        boolean set = redisUtils.set(confirmVo.getOrderKey(), confirmVo, ConstUtil.ORDER_CONFIRM_EXPR_TIME);
        return set ? IResult.ok(confirmVo) : IResult.fail("信息生成失败");
    }

    @ApiOperation(value = "订单 取消预生成", notes = "通过orderKey 取消订单 redis中的")
    @PostMapping("/pre/cancel/{orderKey}")
    public IResult preCancel(@PathVariable("orderKey") String key) {
        redisUtils.del(key);
        return IResult.ok();
    }

    @ApiOperation(value = "订单 计算结果", notes = "通过订单orderKey 计算金额")
    @PostMapping("/computed/{orderKey}")
    public IResult computed(@PathVariable("orderKey") String key, OrderComputedDto computedDto) {
        ConfirmOrderVo vo = (ConfirmOrderVo) redisUtils.get(key);
        if (null == vo) {
            return IResult.fail("订单过期，请刷新");
        }

        return IResult.ok();
    }

    @ApiOperation(value = "订单 提交订单", notes = "通过订单orderKey 创建订单 返回订单流水id --> 支付 or 取消")
    @PostMapping("/create/{orderKey}")
    public IResult createOrder(@PathVariable("orderKey") String key, OrderCreateDto dto) {
        ConfirmOrderVo vo = null;
        try {
            vo = (ConfirmOrderVo) redisUtils.get(key);
            if(vo==null){
                throw new WBusiException("订单已经失效");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new WBusiException("订单已经失效");
        }
        return service.createOrder(vo, dto);
    }

    @ApiOperation(value = "订单 取消订单", notes = "通过订单流水 取消订单")
    @PostMapping("/cancel/{uniKey}")
    public IResult cancelOrder(@PathVariable("uniKey") String key) {
        return IResult.ok("订单取消成功");
    }


    @ApiOperation(value = "订单 详情", notes = "通过订单流水 获取订单详情")
    @GetMapping("/detail/{uniKey}")
    public IResult detailOrder(@PathVariable("uniKey") String key) {

        return IResult.ok("获取订单详情");
    }


    @ApiOperation(value = "订单 退货原因", notes = "退货原因")
    @GetMapping("/refund/reason")
    public IResult reason() {
        List rls = new ArrayList(){{
            add("收货地址填错了");
            add("与描述不符");
            add("信息填错了，重新拍");
            add("收到商品损坏了");
            add("未按预定时间发货");
            add("其它原因");
        }};
        return IResult.ok(rls);
    }

    @ApiOperation(value = "订单 退货校验", notes = "退货校验")
    @PostMapping("/refund/verify")
    public IResult verify(Map<String,String> param) {

//        refund_reason_wap_explain: "测试"
//        refund_reason_wap_img: ""
//        text: "未按预定时间发货"
//        uni: "1284416829816569856"


        return IResult.ok();
    }




}
